package com.jiangjiang.eshop.commodity.operation;

import com.jiangjiang.eshop.commodity.domain.PropertyGroupEntity;
import com.jiangjiang.eshop.commodity.dto.PropertyGroupDTO;
import com.jiangjiang.eshop.commodity.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName RemoveCategoryOperation
 * @Description TODO
 * @Author jhw
 * @Date 2021/7/9 17:53
 * @Version 1.0
 **/
@Component
@Scope("prototype")
public class RemoveCategoryOperation extends AbstractCategoryOperation<Boolean> {

    @Autowired
    private CategoryPropertyRelationshipService categoryPropertyRelationshipService;
    @Autowired
    private PropertyGroupService propertyGroupService;
    @Autowired
    private PropertyGroupRelationshipService relationshipService;

    public RemoveCategoryOperation(CategoryService categoryService) {
        super(categoryService);
    }

    @Override
    protected Boolean doRealExecute(Category category) {
        removePropertyRelation(category.getCategoryId());
        removePropertyGroup(category.getCategoryId());
        return removeCategory(category.getCategoryId());
    }

    /**
     * 删除类目数据
     *
     * @param categoryId 类目主键
     */
    private Boolean removeCategory(Long categoryId) {
        return categoryService.removeById(categoryId);
    }

    /**
     * 删除属性组
     *
     * @param categoryId
     */
    private void removePropertyGroup(Long categoryId) {
        List<PropertyGroupDTO> entityList = propertyGroupService.listByCategoryId(categoryId);
        List<Long> propertyGroupIds = entityList.stream().map(PropertyGroupDTO::getId).collect(Collectors.toList());
        // 批量删除所以属性组和属性间的关联关系
        relationshipService.batchRemoveByPropertyGroupIds(propertyGroupIds);
        // 删除所以属性分组
        propertyGroupService.removeByCategoryId(categoryId);
    }

    /**
     * 删除类目与属性的关联关系
     *
     * @param categoryId 类目id
     */
    private void removePropertyRelation(Long categoryId) {
        categoryPropertyRelationshipService.removeByCategoryId(categoryId);
    }

}
